<template>
  <div
    :class="{
      'rounded-xl': getLayout === 'loose',
      'p-2': getLayout === 'compact',
    }"
    class="p-2 h-full bg-document-list select-none"
  >
    <UIInput size="small" v-model:value="search" placeholder="搜索章节">
      <template #suffix>
        <div class="h-full addSectionBtn">
          <UIButton
            size="small"
            text
            @click="() => newSection()"
            icon-name="Add"
          />
        </div>
      </template>
    </UIInput>
    <n-divider />
    <div
      class="flex flex-col gap-1 overflow-auto h-[calc(100vh-7rem)] mt-2"
      ref="sectionListRef"
      v-if="
        document[nowDocumentIndex].sections.length && nowSectionIndex !== -1
      "
    >
      <n-virtual-list
        :item-size="28"
        ref="virtualListRef"
        :items="document[nowDocumentIndex].sections"
      >
        <template #default="{ item }">
          <div
            v-if="item.title.indexOf(search) !== -1"
            @contextmenu="
              (e) =>
                handleContextmenu(
                  e,
                  item,
                  document[nowDocumentIndex].sections.findIndex(
                    (e) => e.id === item.id
                  )
                )
            "
            :class="{ 'bg-document-list-active': nowSectionId === item.id }"
            class="cursor-pointer hover:bg-document-list-active rounded-md mt-1"
            @click="setSectionId(item.id)"
            @dblclick="item.readonly = false"
            :key="item.id"
          >
            <UIInput
              no-style
              @blur="item.readonly = true"
              :readonly="item.readonly"
              size="small"
              v-model:value="item.title"
              placeholder="无章节标题"
            />
          </div>
        </template>
      </n-virtual-list>
    </div>
  </div>
</template>

<script setup lang="ts">
import { storeToRefs } from "pinia";
import UIInput from "@/components/UI/Input/index.vue";
import { NVirtualList } from "naive-ui";
const virtualListRef =
  useTemplateRef<InstanceType<typeof NVirtualList>>("virtualListRef");
const sectionListRef = useTemplateRef<HTMLDivElement>("sectionListRef");
const search = ref("");
const { nowDocumentIndex, nowSectionIndex, document, nowSectionId } =
  storeToRefs(documentStore());
const { addSection, setNowSectionId, deleteSection } = documentStore();
const { getLayout } = storeToRefs(settingsStore());
const newSection = async () => {
  document.value[nowDocumentIndex.value].sections.forEach((item) => {
    item.readonly = true;
  });
  addSection("新章节");
  await nextTick();
  virtualListRef.value?.scrollTo({ position: "bottom" });
  setTimeout(() => {
    Array.from(sectionListRef.value?.querySelectorAll("input")!)
      .at(-1)
      ?.focus();
  }, 100);
};
const emit = defineEmits<{
  (e: "change-section"): void;
}>();
const setSectionId = (sectionId: string) => {
  setNowSectionId(sectionId);
  emit("change-section");
};
const { showDropDown } = useDropDown([
  {
    label: "重命名",
    key: "rename",
    icon: getIcon("NameSpace", {
      style: { width: "1.2rem", height: "1.2rem" },
    }),
  },
  {
    label: "删除",
    key: "delete",
    icon: getIcon("DeleteOutlined", {
      style: { width: "1.2rem", height: "1.2rem" },
    }),
  },
]);
const menuFunction = {
  rename: async (item: Section, index: number) => {
    item.readonly = false;
    await nextTick();
    Array.from(sectionListRef.value?.querySelectorAll("input")!)[
      index
    ]?.focus();
  },
  delete: (item: Section) => {
    deleteSection(-1, item.id);
  },
};
const handleContextmenu = async (
  e: MouseEvent,
  item: Section,
  index: number
) => {
  e.preventDefault();
  const key = await showDropDown<keyof typeof menuFunction>(e);
  if (key) {
    menuFunction[key](item, index);
  }
};
</script>

<style>
.addSectionBtn {
  display: flex;
  align-items: center;

  div[size="small"] {
    display: contents;
  }
}
</style>
